package org.syndicate.domain;

import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

/**
 * Expresses how to share SharePie.<br/>
 * SharePie shares a pie by percent.
 * 
 * @author akiraabe
 */
@RooJavaBean
@RooToString
@RooEntity(inheritanceType = "JOINED")
public class PercentPie extends SharePie {

	/**
	 * {@inheritDoc}
	 */
	@Transactional
	@Override
	public void create() {
		System.out.println("PercentPie#create");
		Double amount = 0.0;
		for (Share share : getShares()) {
			amount += share.getAmount();
		}
		if (amount < 0.99999 || amount > 1.00001) {
			System.out.println(amount);
			throw new RuntimeException();
		}
		this.setAmount(amount);
		this.setDiscriminator("PercentPie");
	}

	/**
	 * Prorate new share pie.
	 * SharePie is shared according to the ratio.
	 * 
	 * @param amount of SharePie
	 * @return new <b>AmountPie</b> that includes some shares.
	 */
	@Override
	public SharePie prorate(Double amount) {
		System.out.println("PercentPie#prorate");

		SharePie newSharePie = new AmountPie();
		newSharePie.setAmount(amount);
		newSharePie.setDiscriminator("AmountPie");
		for (Share share : this.getShares()) {
			Share newShare = new Share();
			newShare.setAmount(amount * share.getAmount());
			newShare.setOwner(share.getOwner());
			newSharePie.addShare(newShare);
		}
		return newSharePie;
	}
}
